package com.uxsino.commons.logicSelector.propFunction;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uxsino.commons.logicSelector.PropProxy;

/**
 * 
 *
 */
public class PropProxyValueFunction implements IPropValueFunction {
    private static Logger logger = LoggerFactory.getLogger(PropProxyValueFunction.class);

    private String propName;

    private List<Method> proxyMethods;

    protected PropProxyValueFunction(List<Method> methods, String propName) {
        this.propName = propName;
        this.proxyMethods = methods;
    }

    public static PropProxyValueFunction create(Class<?> cls, String propName) {
        List<Method> proxyMethods = new ArrayList<Method>();

        for (Method method : cls.getMethods()) {
            if (method.getAnnotation(PropProxy.class) != null) {
                proxyMethods.add(method);
            }
        }
        if (proxyMethods.size() > 0) {
            return new PropProxyValueFunction(proxyMethods, propName);
        }
        return null;
    }

    @Override
    public Object get(Object object) {

        if (object == null) {
            logger.error("refer to null object.prop:{}", propName);
            return null;
        }
        Object result = null;
        for (Method method : proxyMethods) {
            try {
                result = method.invoke(object, propName);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                logger.error("error getting proxyMethod value. {}", "", e);
            }
            if (result != null) {
                return result;
            }
        }
        return null;
    }

}
